﻿using System;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using ContractManager.Entity;
using ContractManager.BLL.Business;
using DevExpress.XtraEditors;

namespace ContractManager.Systems.Forms
{
    public partial class FrmLogin : XtraFormBase
    {
        #region "Define Variable"
        public FrmMain FrmMain;
        public bool LoginFlag;
        private DataView _dvMcy = new DataView();
        private string _strUserName;
        private string _strPassword;
        private int _mcyId;
        private int _yearId;
        private string _companyName;
        private string _companyCode;
        #endregion

        #region "Construction"
        public FrmLogin()
        {
            InitializeComponent();
        }

        #endregion

        #region "Private Method"

        private void GetCompany()
        {
            try
            {
                DataTable dtCompay = ClsMyCo.GetAll();
                txtMCY.Properties.DataSource = dtCompay;
                txtMCY.Properties.DisplayMember = "AS_Sys_Company_Info_Name";
                txtMCY.Properties.ValueMember = "AS_Sys_MyCo_Year_ID";
                txtMCY.Properties.PopulateColumns();
                _mcyId = Convert.ToInt32(dtCompay.Rows[0]["AS_Sys_MyCo_Year_ID"]);

                _yearId = DateTime.Now.Year;
                //_yearId = Convert.ToInt32(dtCompay.Rows[0]["AS_Sys_Year_ID"]);
                _companyCode = String.Format("{0}", dtCompay.Rows[0]["AS_Sys_Company_Info_Tax_Code"]);
                _companyName = txtMCY.Text;
                txtMCY.EditValue = _mcyId;
                _dvMcy = dtCompay.DefaultView;
                txtMCY.Properties.Columns["AS_Sys_Company_Info_Name"].Width = 250;
                txtMCY.Properties.Columns["AS_Sys_Year_ID"].Width = 100;
                txtMCY.Properties.Columns["AS_Sys_Company_Info_Name"].Caption = @"Tên đơn vị";
                txtMCY.Properties.Columns["AS_Sys_Year_ID"].Caption = @"Năm làm việc";

                txtMCY.Properties.Columns[0].Visible = false;
                txtMCY.Properties.Columns[1].Visible = false;
                txtMCY.Properties.Columns[4].Visible = false;
                txtMCY.Properties.Columns[5].Visible = false;
                txtMCY.Properties.Columns[6].Visible = false;
                txtMCY.Properties.Columns[7].Visible = false;
            }
            catch (Exception e)
            {
                XtraMessageBox.Show("Có lỗi xảy ra trong quá trình nạp danh mục đơn vị " + e.Message, "Thông báo");
            }
        }
        #endregion

        #region "Form Event"
        private void FrmLoginLoad(object sender, EventArgs e)
        {
            GetCompany();
        }
        #endregion

        #region "Button Event"

        private void BtnOkClick(object sender, EventArgs e)
        {
            #region "Check Condition"
            if (txtMCY.EditValue == null)
            {
                XtraMessageBox.Show(
                    "Tên đơn vị không được để trống.",
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                txtMCY.SelectAll();
                txtMCY.Focus();
                return;
            }
            if (txtUserName.EditValue == null 
                || txtUserName.Text.Length==0)
            {
                XtraMessageBox.Show(
                    "Tên đăng nhập không được để trống.",
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                txtUserName.SelectAll();
                txtUserName.Focus();
                return;
            }
            #endregion

            _strUserName = String.Format("{0}", txtUserName.EditValue);
            _strPassword = String.Format("{0}", txtPassword.EditValue);
            _strUserName = _strUserName.Trim();
            _strPassword = _strPassword.Trim();

            if (_strUserName == "")
            {
                txtUserName.Focus();
            }
            else
            {
                try
                {
                    var user = ClsEmployees.SelectByUserName(_strUserName);
                    if (user != null )
                    {
                       // Employees emp = user[0];

                        ClsVariable.Year = _yearId;
                        ClsVariable.AsSysMyCoYearId = _mcyId;
                        ClsVariable.CompanyName = _companyName;
                        ClsVariable.CompanyCode = _companyCode;

                        ClsVariable.EmployeeId = user.ID;
                        ClsVariable.UserName = user.UserName;
                        ClsVariable.PassWord = user.Password;
                        ClsVariable.FullName = user.FullName;
                        ClsVariable.RoleNo = user.DepartmentId;
                        if (user.MbID.HasValue) ClsVariable.MemberBranchId = Convert.ToInt32(user.MbID);

                        ClsVariable.IsEditVoucher = Convert.ToBoolean(user.IsEditVoucher);

                        if (ClsVariable.Encrypt(_strPassword).Equals(ClsVariable.PassWord))
                        {

                            LoginFlag = true;
                            ClsVariable.IsLogin = LoginFlag;
                            ClsVariable.DtParam = ClsParameter.GetAll();
                            ClsVariable.DtContractDetails = ClsContracts.ListDetail(0);
                            ClsVariable.DtDocumentDetails = ClsDocuments.ListDetail(0);
                            ClsVariable.DtRevenueDetails = ClsRevenues.ListDetail(0);
                            ClsVariable.DtPlanRevenueDetails = ClsPlanRevenues.ListDetail(0);

                            Close();
                            if (FrmMain != null)
                            {
                                FrmMain.barMenu.ClearLinks();
                                FrmMain.LoadMenu();
                            }
                        }
                        else
                        {
                            txtUserName.EditValue = "";
                            txtPassword.EditValue = "";
                            XtraMessageBox.Show(
                                "Mật khẩu không đúng, vui lòng thử lại..!!",
                                "Thông báo",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error
                                );
                            txtUserName.Focus();
                        }
                    }
                    else
                    {
                        txtUserName.EditValue = "";
                        txtPassword.EditValue = "";
                        XtraMessageBox.Show(
                            "Tên đăng nhập hoặc mật khẩu không đúng, vui lòng thử lại..!!",
                            "Thông báo",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error
                            );
                        txtUserName.SelectAll();
                        txtUserName.Focus();
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(
                            "Có lỗi xảy ra trong quá trình đăng nhập..!! " + ex.Message,
                            "Thông báo",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error
                            );
                    
                }
                
                  
            }
        }

        private void BtnExitClick(object sender, EventArgs e)
        {
            // Kiểm tra xem nếu người dùng chưa Login thì thoát khởi chương trình
            // Ngược lại thì đóng Form Login
            if (!ClsVariable.IsLogin)
                Application.Exit();
            else
                Close();
        }


        private void TxtMcyEditValueChanged(object sender, EventArgs e)
        {
            if (txtMCY.EditValue != null)
            {
                _dvMcy.RowFilter = "";
                _dvMcy.RowFilter = String.Format("AS_Sys_MyCo_Year_ID={0}", txtMCY.EditValue);
                if (_dvMcy.Count > 0)
                {
                    _mcyId = Convert.ToInt32(txtMCY.EditValue);
                    _yearId = DateTime.Now.Year;
                    _companyCode = String.Format("{0}", _dvMcy[0]["AS_Sys_Company_Info_Tax_Code"]);
                    _companyName = txtMCY.Text;
                }
                _dvMcy.RowFilter = "";
            }
        }
        #endregion

        #region "mouse move the form"
        Point _mouseOff;
        bool _leftFlag;
        private void FrmLogin_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y); 
                _leftFlag = true;                  
            }
        }

        private void FrmLogin_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);  
                Location = mouseSet;
            }
        }

        private void FrmLogin_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }
        #endregion

       
        #region "round form"

        private void FrmLogin_Resize(object sender, EventArgs e)
        {
            Region = null;
            SetWindowRegion();
        }
        public void SetWindowRegion()
        {
            System.Drawing.Drawing2D.GraphicsPath FormPath;
            FormPath = new System.Drawing.Drawing2D.GraphicsPath();
            Rectangle rect = new Rectangle(0, 22, this.Width, this.Height - 22);//this.Left-10,this.Top-10,this.Width-10,this.Height-10);                
            FormPath = GetRoundedRectPath(rect, 50);
            this.Region = new Region(FormPath);
        }
        private GraphicsPath GetRoundedRectPath(Rectangle rect, int radius)
        {
            int diameter = radius;
            Rectangle arcRect = new Rectangle(rect.Location, new Size(diameter, diameter));
            GraphicsPath path = new GraphicsPath();
            //   ×óÉÏ½Ç  
            path.AddArc(arcRect, 180, 90);
            //   ÓÒÉÏ½Ç  
            arcRect.X = rect.Right - diameter;
            path.AddArc(arcRect, 270, 90);
            //   ÓÒÏÂ½Ç  
            arcRect.Y = rect.Bottom - diameter;
            path.AddArc(arcRect, 0, 90);
            //   ×óÏÂ½Ç  
            arcRect.X = rect.Left;
            path.AddArc(arcRect, 90, 90);
            path.CloseFigure();
            return path;
        }
        #endregion




    }
}